<template>
  <el-row style="min-width: 1500px">
    <el-col :span="24">
      <div class="program_flex_box x-flex">
        <div class="wrap_left_grouping">
          <div class="wrap_left_grouping--head-title x-flex x-row-between">
            <text>账户列表</text>
            <el-button
              text
              type="primary"
              @click="dialogVisible = true"
              v-has="'userAddgrouping'"
              ><img alt="+" class="x-m-r-6" src="@/assets/Add.svg" />新增分组
            </el-button>
          </div>
          <el-dialog v-model="dialogVisible" @close="clearAd" width="30%">
            <template #header="{ titleId, titleClass }">
              <div class="my-header">
                <h4
                  :id="titleId"
                  :class="titleClass"
                  style="display: flex; align-items: center"
                >
                  <div class="add"></div>
                  <div style="margin: 0 5px">{{ userINfo }}</div>
                </h4>
              </div>
            </template>
            <el-input
              @input="btnAdd"
              v-model="addTreeName"
              placeholder="请输入分组名称"
              maxlength="20"
            />
            <div v-if="addIN" style="color: red">分组名称不能为空</div>
            <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" @click="onAddTreeName">
                  添加
                </el-button>
              </span>
            </template>
          </el-dialog>
          <div class="wrap_left_grouping--content-area">
            <el-tree
              :data="trees"
              default-expand-all
              @node-click="nodeClick"
              :expand-on-click-node="false"
            >
              <template #default="{ node, data }">
                <div class="x-flex x-row-between x-flex1">
                  <span v-if="!data.isEditNode">{{ node.label }}</span>
                  <div
                    v-has="
                      'facility-Addgroup' ||
                      'facility-Editgroup' ||
                      'facilityDelete'
                    "
                  >
                    <el-dropdown v-if="!data.isAddNode">
                      <span style="outline: none">
                        <el-icon color="#a8abb2"><MoreFilled /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item
                            @click.stop="addAllNode(node, data)"
                            v-has="'facility-Addgroup'"
                            >创建子分组
                          </el-dropdown-item>
                          <el-dropdown-item
                            @click.stop="editStop(node, data)"
                            v-has="'facility-Editgroup'"
                            >重命名
                          </el-dropdown-item>
                          <el-dropdown-item
                            @click.stop="delAllNode(node, data)"
                            v-has="'facilityDelete'"
                            >删除
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
                <br />
              </template>
            </el-tree>
          </div>
        </div>
        <div class="wrap_right_list">
          <div class="wrap_right_list--head-title">
            <text>账户列表</text>
          </div>
          <div class="wrap_right_list--head-operation x-scroll">
            <div class="x-flex">
              <div class="x-m-r-12">
                <el-button
                  size="large"
                  type="primary"
                  @click="openClick"
                  v-has="'Adduser'"
                  >新增子账号
                </el-button>
                  <el-button
                  size="large"
                  style="margin: 0 15px; color: #0daeff; border-color: #0daeff"
                  @click="onEquipInfo('1')"
                  v-has="'Adduserrole'"
                  >新增角色</el-button
                >
                <!-- 新增账号弹框 -->
                <el-dialog
                  v-model="isUploadMaterial"
                  width="30%"
                  @close="closeClick"
                >
                  <template #header="{ titleId, titleClass }">
                    <div class="my-header">
                      <h4
                        :id="titleId"
                        :class="titleClass"
                        style="display: flex; align-items: center"
                      >
                        <div class="add"></div>
                        <div style="margin: 0 5px">{{ title }}</div>
                      </h4>
                    </div>
                  </template>
                  <el-form
                    ref="equipFormRef"
                    :model="equipForm"
                    :rules="equipRules"
                    label-position="left"
                    label-width="95px"
                  >
                    <div>
                      <div>
                        <div class="-addEquip_minHead">基本信息</div>
                        <el-form-item label="用户名" prop="eNo">
                          <el-input
                            v-model="equipForm.eNo"
                            placeholder="请输入"
                            :disabled="disableds"
                            maxlength="15"
                          />
                        </el-form-item>
                        <el-form-item label="姓名" prop="eName">
                          <el-input
                            v-model="equipForm.eName"
                            placeholder="请输入"
                            maxlength="15"
                          />
                        </el-form-item>
                        <el-form-item label="密码" prop="pas">
                          <el-input
                            v-model="equipForm.pas"
                            maxlength="15"
                            show-word-limit
                            :placeholder="placeholders"
                            @input="inputSize = true"
                          />
                          <span
                            v-if="!inputSize"
                            style="color: red; font-size: 12px"
                            >不填即为默认密码(Ab1234567)</span
                          >
                        </el-form-item>
                        <div class="-addEquip_minHead">分组与角色</div>
                        <el-form-item label="分组" prop="eEquipName">
                          <div class="-addDialogFormInput e-l-cascader">
                            <el-cascader
                              style="width: 378px"
                              v-model="equipForm.eEquipName"
                              ref="regionRef"
                              :options="trees"
                              :props="regionProps"
                              clearable
                              placeholder="请选择分组"
                              @change="regionRefClick"
                            />
                          </div>
                        </el-form-item>
                        <el-form-item label="角色" prop="role">
                          <div class="-addDialogFormInput e-l-cascader">
                            <el-cascader
                              v-model="equipForm.role"
                              ref="regionRefs"
                              :options="treesd"
                              :props="regionPropsd"
                              style="width: 378px"
                              clearable
                              placeholder="请选择角色"
                              @change="regionRefClicks"
                            />
                          </div>
                        </el-form-item>
                        <div class="-addEquip_minHead">登录</div>
                        <el-form-item label="手机号" prop="eResponsible">
                          <el-input
                            v-model="equipForm.eResponsible"
                            placeholder="请输入"
                          />
                        </el-form-item>
                        <el-form-item label="邮箱" prop="eRegion">
                          <el-input
                            v-model="equipForm.eRegion"
                            placeholder="请输入"
                          />
                        </el-form-item>
                      </div>
                    </div>
                  </el-form>
                  <template #footer>
                    <span>
                      <el-button @click="resetEquipForm">取消</el-button>
                      <el-button
                        type="primary"
                        @click="submitAddEquipForm(equipFormRef)"
                      >
                        确定
                      </el-button>
                    </span>
                  </template>
                </el-dialog>
                <!-- 新增角色弹框 -->
                <el-dialog v-model="dialogFormVisibles" width="70%">
                  <template #header="{ titleId, titleClass }">
                    <div class="my-header">
                      <h4
                        :id="titleId"
                        :class="titleClass"
                        style="display: flex; align-items: center"
                      >
                        <div class="add"></div>
                        <div style="margin: 0 5px">新增角色</div>
                      </h4>
                    </div>
                  </template>
                  <div style="display: flex; align-items: center">
                    <span style="margin: 0 10px">角色名称 </span>
                    <el-input
                      style="width: 200px; align-items: center"
                      v-model="roseInput"
                      maxlength="20"
                    ></el-input>
                  </div>
                  <div class="e-l-dialog_box">
                    <div class="x-flex x-row-between x-m-b-20">
                      <div style="margin: 10px 0">
                        <el-menu
                          :default-active="infoEquipCount"
                          :ellipsis="false"
                          class="el-menu-demo"
                          mode="horizontal"
                          @select="Onselect"
                          style="display: flex"
                        >
                          <el-menu-item index="1">信发PC端</el-menu-item>
                          <el-menu-item index="2">信发小程序</el-menu-item>
                        </el-menu>
                      </div>
                    </div>
                  </div>
                  <div v-show="infoEquipCount == '1'">
                    <el-tree
                      :data="roleData"
                      show-checkbox
                      node-key="id"
                      ref="subRoleTree"
                      :props="defaultProps"
                      default-expand-all
                      @check-change="checkRole"
                    />
                  </div>
                  <div v-show="infoEquipCount == '2'">
                    <el-tree
                      :data="roleDatas"
                      default-expand-all
                      show-checkbox
                      node-key="id"
                      ref="subRoleTree"
                      :props="defaultProps"
                      @check-change="checkRole"
                    />
                  </div>
                  <template #footer>
                    <span class="dialog-footer">
                      <el-button @click="dialogFormVisibles = false"
                        >取消</el-button
                      >
                      <el-button type="primary" @click="openRole">
                        确定
                      </el-button>
                    </span>
                  </template>
                </el-dialog>
              </div>
              <el-dropdown
                ref="dropdownGrouping"
                class="x-m-l-12"
                trigger="contextmenu"
              >
                <el-button
                  size="large"
                  @click="changeGrouping(tableData)"
                  v-has="'userBatchpause'"
                  >暂停
                </el-button>
                <template #dropdown>
                  <div class="x-p-8">请选择文件</div>
                </template>
              </el-dropdown>
              <el-dropdown
                ref="dropdownGroupings"
                class="x-m-l-12"
                trigger="contextmenu"
              >
                <el-button
                  size="large"
                  @click="changeGroupings(tableData)"
                  v-has="'userbatchActivation'"
                  >启用
                </el-button>
                <template #dropdown>
                  <div class="x-p-8">请选择文件</div>
                </template>
              </el-dropdown>
            </div>
            <div class="x-flex">
              <el-input
                v-model="searchInput"
                :suffix-icon="Search"
                placeholder="请输入用户名/姓名/手机号"
                size="large"
                style="cursor: pointer; width: 220px; margin-right: 26px"
                @change="SearchClick"
              />
              <el-button
                style="width: 70px"
                size="large"
                text
                type="primary"
                @click="AdvancedSearchShow = !AdvancedSearchShow"
              >
                <div>高级搜索</div>
                <el-icon
                  :class="{ 'angle-icon': AdvancedSearchShow }"
                  style="margin-right: 26.4%"
                >
                  <ArrowDown />
                </el-icon>
              </el-button>
            </div>
          </div>
          <div
            v-show="AdvancedSearchShow"
            style="margin-bottom: 16px !important"
            class="-advancedInput x-flex"
          >
            <div class="-addDialogFormInput e-l-cascader">
              <el-select
                v-model="equipForm.role"
                class="x-m-r-12"
                style="width: 10.6vw"
                ref="regionRefs"
                placeholder="请选择角色"
                size="large"
              >
                <el-option
                  v-for="item in treesd"
                  :label="item.label"
                  :value="item.value"
                  @click="roleClick(item.value)"
                />
              </el-select>
            </div>
            <el-select
              v-model="equipForm.Status"
              class="x-m-r-12"
              style="width: 10.6vw"
              placeholder="请选择状态"
              size="large"
            >
              <el-option label="已启用" @click="addElemt" value="0" />
              <el-option label="已暂停" @click="addElemts" value="1" />
            </el-select>
            <div></div>
            <el-button size="large" @click.stop="onCancel">
              <el-icon>
                <RefreshLeft />
              </el-icon>
            </el-button>
          </div>
          <div class="wrap_right_list--table-content">
            <el-table
              ref="multipleTableRef"
              :data="tableData"
              :header-cell-style="{ background: '#F6F7F9' }"
              :row-style="{ height: '64px' }"
              height="calc(90vh - 240px)"
              style="width: 100%; z-index: 1"
              @selection-change="handleSelectionChange"
            >
              <template #empty>
                <div class="no-data">
                  <el-empty
                    :image="require('../../assets/nothave.png')"
                    style="margin-top: 30%"
                  >
                  </el-empty>
                </div>
              </template>
              <el-table-column type="selection" width="40" />
              <el-table-column
                label="用户名"
                property="account"
                show-overflow-tooltip
                width="150"
              >
              </el-table-column>
              <el-table-column label="姓名" width="120">
                <template #default="{ row }">
                  <div v-if="row.name">
                    {{ row.name }}
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="80">
                <template #default="{ row }">
                  <div v-if="row.usable == 0">已启用</div>
                  <div v-if="row.usable == 1">已暂停</div>
                </template>
              </el-table-column>
              <el-table-column label="手机号" property="phone" width="180" />
              <el-table-column label="角色" property="roleName" width="120" />
              <el-table-column label="分组" width="180">
                <template #default="{ row }">
                  <div>{{ row.groupId }}</div>
                </template>
              </el-table-column>
              <el-table-column label="IP地址" property="loginIp" width="140" />

              <el-table-column
                label="操作"
                style="display: flex; align-items: center"
              >
                <template #default="{ row }">
                  <div style="display: flex; align-items: center">
                    <el-button
                      size="small"
                      text
                      type="primary"
                      @click="copyTableObj(row.id)"
                      style="margin: 0 -10px"
                      v-has="'useoncebape'"
                      >暂停
                    </el-button>
                    <el-button
                      size="small"
                      text
                      type="primary"
                      @click="copyTableObjs(row.id)"
                      v-has="'useoncebati'"
                      >启用
                    </el-button>
                    <el-button
                      size="small"
                      text
                      @click="editclick(row)"
                      type="primary"
                      v-has="'useoncebape'"
                      >编辑
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="-pages">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 40]"
                :total="total"
                background
                layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>

            <el-dialog v-model="dialogFormVisible" title="复制" width="30%">
              <el-form :model="form" center>
                <el-form-item label="节目名称:" label-width="140px">
                  <el-input v-model="form.name" autocomplete="off" />
                </el-form-item>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="dialogFormVisible = false">取消</el-button>
                  <el-button type="primary" @click="ConfirmCopy">
                    确认
                  </el-button>
                </span>
              </template>
            </el-dialog>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import {
  onMounted,
  reactive,
  ref,
  shallowRef,
  unref,
  watch,
  getCurrentInstance,
} from "vue";
import {
  ArrowDown,
  MoreFilled,
  Search,
  RefreshLeft,
} from "@element-plus/icons-vue";
import type {
  DropdownInstance,
  FormInstance,
  FormRules,
  CascaderProps,
} from "element-plus";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import {
  resolutionList,
  CopyOpenprogram,
} from "@/api/advertising";
import {
  structure,
  AddStructure,
  EditStructure,
  DelectStructure,
  uderPage,
  rolePage,
  AddProgramUser,
  editUser,
  editProgramUser,
  batchPause,
  batchActivation,
  roleLink,
  AllsysMenu,
} from "@/api/userManagement/index";
import { convertDatads, convertDatade, convertDataA } from "@/utils/list";
const equipFormRef = ref<FormInstance>();
// 复制弹框
const dialogFormVisible = ref(false);
// 复制弹框里面的inoput
const form = reactive({
  name: "",
});
//新增分组
const dialogVisible = shallowRef(false);
const addTreeName = shallowRef("");
const TreeValue = ref(0);
// 新增子账户
var placeholders = ref<any>("请输入");
var inputInfo = ref<any>("请输入");
var disableds = ref(false);
const instance: any = getCurrentInstance();
//树形控件
const trees = ref<Tree[] | null>(null);
const treesd = ref<Tree[] | null>(null);
// 暂停/启用按钮状态
const dropdownGrouping = ref<DropdownInstance>();
const dropdownGroupings = ref<DropdownInstance>();
const dialogFormVisibles = ref(false);

//新增节目/发布广告
const isUploadMaterial = shallowRef(false);

const formInline = reactive({
  programName: "",
  programType: "",
  programResolution: "",
  programCustom: "", //自定义宽高
  wide: "", //宽
  High: "", //高
});
watch(
  () => formInline,
  (newVal) => {
    if (newVal.wide || newVal.High) {
      formInline.programCustom = `${newVal.wide}x${newVal.High}`;
    } else {
      formInline.programCustom = "";
    }
  },
  { deep: true }
);
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  programName: [{ required: true, message: "请填写节目名称", trigger: "blur" }],
  programType: [{ required: true, message: "请选择类型", trigger: "change" }],
  programResolution: [
    { required: true, message: "请选择分辨率", trigger: "change" },
  ],
  programCustom: [{ required: true, message: "请输入宽高", trigger: "blur" }],
});
var ishow = ref("1");
var title = ref("新增账户");
const openClick = async () => {
  isNewDevice.value = true;
  ishow.value = "1";
  title.value = "新增账户";
  //   isAddEdit.value = false;
  disableds.value = false;
  isUploadMaterial.value = true;
  placeholders.value = "请输入";
  inputInfo.value = "请输入";
  placeholders.value = "不填即为默认密码（Ab1234567）";
  equipForm.pas = "Ab1234567";
  const res = await rolePage();
  treesd.value = convertDatade(res.data.data);
};
// 清除搜索框
const onCancel = () => {
  for (let key in equipForm) {
    equipForm[key] = "";
  }
  userId.value = "";
  paging();
};
const roleClick = (val: any) => {
  equipForm.role = val;
  paging();
};
var userId = ref("");
const addElemt = () => {
  userId.value = "0";
  paging();
};
const addElemts = () => {
  userId.value = "1";
  paging();
};
// 新增角色props配置
const defaultProps = {
  children: "children",
  label: "label",
};
// 新增角色数据
const roleData = ref();
const roleDatas = ref();
const options = shallowRef([]);
const activeName = ref("first");
const infoEquipCount = shallowRef("1");
const radioControl = ref("xinfa");
//新增角色弹框按钮
const onEquipInfo = async (num: string | number) => {
  radioControl.value = "xinfa";
  dialogFormVisibles.value = true;
  num == "1" ? (infoEquipCount.value = "1") : (infoEquipCount.value = "2");
  sysMenus();
};

const sysMenus = async () => {
  let data = {
    linkSystem: radioControl.value,
  };
  let res = await AllsysMenu(data);
  roleData.value = convertDataA(res.data.data);
};
// 获取菜单列表
const Onselect = async (vals: any) => {
  infoEquipCount.value = vals;
  let val = ref(vals);
  if (val.value == "1") {
    radioControl.value = "xinfa";
    let data = {
      linkSystem: radioControl.value,
    };
    let res = await AllsysMenu(data);
    roleData.value = convertDataA(res.data.data);
  } else if (val.value == "2") {
    let data = {
      linkSystem: (radioControl.value = "xinfaXcx"),
    };

    let res = await AllsysMenu(data);
    roleDatas.value = convertDataA(res.data.data);
  }
};
const roseInput = ref("");
const valId = ref([]);

// 新增角色接口
const openRole = async () => {
  if (!valId.value) {
    ElMessage.error("请选择功能权限");
    return;
  }
  roseInput.value;
  if (!roseInput.value) {
    ElMessage({ message: "请输入角色名称", type: "error", duration: 1000 });
    return;
  }
  let data = {
    menuIds: valId.value,
    roleId: "",
    roleName: roseInput.value,
    linkSystem: "xinfa",
  };

  let res = await roleLink(data);
  if (res.data.code == 1) {
    paging();
    dialogFormVisibles.value = false;
    ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
  } else {
    ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
  }
};
const subRoleTree = ref();

const checkRole = (node: { checked: any }, data: { value: any }) => {
  if (data) {
    // 添加选中的ID到selectedIds数组中
    valId.value.push(node.value);
  } else {
    // 从selectedIds数组中移除取消选中的ID
    const index = valId.value.indexOf(node.value);
    if (index > -1) {
      valId.value.splice(index, 1);
      if (node.children.length > 0) {
        valId.value.push(node.value);
      }
    }
  }
};

//表格数据
var tableData: any = ref([]);
// 获取用户分组列表
const getTreeData = async () => {
  const { data } = await structure();
  if (data.code !== 1)
    return ElMessage({ message: data.msg, type: "error", duration: 1000 });
  trees.value = convertDatads(data.data);
};
var addIN = ref(false);
const clearAd = () => {
  addTreeName.value = "";
  addIN.value = false;
};
const btnAdd = (val: any) => {
  if (val) {
    addIN.value = false;
  } else {
    addIN.value = true;
  }
};
const userINfo = ref("新增分组");
var edpid = ref("");
var newObj = ref({});
// 新增分组/子分组/编辑分组确定
const onAddTreeName = async () => {
  if (addTreeName.value) {
    addIN.value = false;
  } else {
    addIN.value = true;
  }

  const params = {
    organizationName: unref(addTreeName),
    pid: 0,
    objectVersionNumber: objectVersionNumbers.value,
  };
  if (userINfo.value == "新增分组") {
    if (addTreeName.value) {
      const { data } = await AddStructure(params);
      if (data.code !== 1)
        return ElMessage({ message: data.msg, type: "error", duration: 1000 });
      await getTreeData();
      ElMessage({ message: data.msg, type: "success", duration: 1000 });
      dialogVisible.value = false;
    }
  } else if (userINfo.value == "添加子分组") {
    if (addTreeName.value) {
      const paramss = {
        organizationName: unref(addTreeName),
        pid: edpid.value,
        objectVersionNumber: objectVersionNumbers.value,
      };
      const { data } = await AddStructure(paramss);
      if (data.code !== 1)
        return ElMessage({ message: data.msg, type: "error", duration: 1000 });
      await getTreeData();
      ElMessage({ message: data.msg, type: "success", duration: 1000 });
      dialogVisible.value = false;
    }
  } else if (userINfo.value == "编辑分组") {
    EditStructure(newObj.value)
      .then(({ data }) => {
        if (data.code !== 1)
          return ElMessage({
            message: data.msg,
            type: "error",
            duration: 1000,
          });
        getTreeData();
        ElMessage({ message: data.msg, type: "success", duration: 1000 });
        dialogVisible.value = false;
        addTreeName.value = "";
      })
      .catch((e) => {});
  }
};
//新增子分组
const addAllNode = (node: any, data: Tree) => {
  dialogVisible.value = true;
  userINfo.value = "添加子分组";
  edpid.value = data.value;
};
// 新增分组按钮
const addBut = () => {
  dialogVisible.value = true;
  userINfo.value = "新增分组";
};

// 编辑分组
const editStop = (node: any, data: Tree) => {
  addTreeName.value = data.label;
  dialogVisible.value = true;
  userINfo.value = "编辑分组";
  edpid.value = data.value;
  let { label, objectVersionNumber, pid, value } = data;

  newObj.value = {
    pid: pid ? pid.toString() : "0",
    organizationName: addTreeName.value ? addTreeName : label,
    id: value,
    objectVersionNumber,
  };
};
//删除假数据一级子类
const removeTreeNode = (node: any, data: Tree) => {
  const parent = node.parent;
  const children = parent.data.children || parent.data;
  const index = children.findIndex((d: Tree) => d.value == data.value);
  children.splice(index, 1);
};
//新增一级子类
const handleAddNode = (node: any, data: Tree) => {
  let params = {
    organizationName: data.name,
    pid: TreeValue.value,
    objectVersionNumber: objectVersionNumbers.value,
  };
  AddStructure(params).then(({ data: res }) => {
    if (res.code !== 1)
      return ElMessage({ message: res.msg, type: "error", duration: 1000 });
    getTreeData();
    ElMessage({ message: res.msg, type: "success", duration: 1000 });
  });
  data.isAddNode = false;
};
//  编辑
const handleEditNode = (node: any, data: Tree) => {
  let { label, objectVersionNumber, pid, value } = data;

  let newObj = {
    pid: pid ? pid : 0,
    organizationName: label,
    id: value,
    objectVersionNumber,
  };
  EditStructure(newObj)
    .then(({ data }) => {
      if (data.code !== 1)
        return ElMessage({ message: data.msg, type: "error", duration: 1000 });
      getTreeData();
      ElMessage({ message: data.msg, type: "success", duration: 1000 });
    })
    .catch((e) => {});
  data.isEditNode = false;
};

const delAllNode = (node: any, data: Tree) => {
  ElMessageBox.confirm("是否确认删除该数据?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(async () => {
      let { data: res } = await DelectStructure(data.value);
      if (res.code !== 1) {
        ElMessage({ message: res.msg, type: "error", duration: 1000 });
      } else {
        ElMessage({ message: res.msg, type: "success", duration: 1000 });
      }
      await getTreeData();
    })
    .catch((e) => {});
};

//表单部分
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<programMsgTable[]>([]);
const id = ref([]);
var list = ref();
//勾选表单时触发
const handleSelectionChange = (val: programMsgTable[]) => {
  list.value = JSON.parse(JSON.stringify(val));

  id.value = list.value.map((a: { id: any }) => a.id);
  multipleSelection.value = val;
};

const equipForm = reactive<TscEquip>({
  eNo: "",
  eName: "",
  eEquipName: [],
  role: [],
  eResponsible: "",
  eRegion: [],
  pas: "",
  Version: "",
  ids: "",
  Status: "",
});
const equipRules = reactive<FormRules>({
  eNo: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const reg = /^[^\u4e00-\u9fff]*$/;
        // eslint-disable-next-line no-console
        if (!reg.test(equipForm.eNo)) {
          callback(new Error("不能输入中文格式的用户名,请重新输入"));
        } else {
          callback();
        }
      },
    },
  ],
  pas: [
    {
      validator: (rule, value, callback) => {
        const reg = /^[A-Z].{5,14}$/;
        // eslint-disable-next-line no-console
        if (!reg.test(equipForm.pas)) {
          callback(new Error("输入的密码格式不正确或者长度不够6位,请重新输入"));
        } else {
          callback();
        }
      },
    },
  ],
  eEquipName: [{ required: true, message: "请选择分组", trigger: "blur" }],
  role: [{ required: true, message: "请选择角色", trigger: "blur" }],
  eResponsible: [
    {
      validator: (rule, value, callback) => {
        const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        // eslint-disable-next-line no-console
        if (value) {
          if (!reg.test(equipForm.eResponsible)) {
            callback(new Error("输入的手机号不正确,请重新输入"));
          } else {
            callback();
          }
        }
      },
    },
  ],
  eRegion: [
    {
      validator: (rule, value, callback) => {
        const reg = /^[\w.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        // eslint-disable-next-line no-console
        if (value) {
          if (!reg.test(equipForm.eRegion)) {
            callback(new Error("输入的邮箱不正确,请重新输入"));
          } else {
            callback();
          }
        }
      },
    },
  ],
});
const regionProps: CascaderProps = {
  expandTrigger: "hover",
  checkStrictly: true,
};
const regionPropsd: CascaderProps = {
  expandTrigger: "hover",
  checkStrictly: true,
};

var regionRefs = ref();
const regionRefClicks = (val: any) => {
  //  拿到选的角色id
  roseId.value = val.join(",");
  regionRefs.value.togglePopperVisible();
};

var regionRef = ref();
const regionRefClick = () => {
  regionRef.value.togglePopperVisible();
};

const isNewDevice = shallowRef(false);
const resetEquipForm = () => {
  isUploadMaterial.value = false;
  inputSize.value = false;
  // 清除表单验证
  if (equipFormRef.value) {
    equipFormRef.value.resetFields();
  }
  for (let key in equipForm) {
    equipForm[key] = "";
  }
};
const closeClick = () => {
  isUploadMaterial.value = false;
  inputSize.value = false;
  // 清除表单验证
  if (equipFormRef.value) {
    equipFormRef.value.resetFields();
  }
  for (let key in equipForm) {
    equipForm[key] = "";
  }
};
var placeholders = ref("不填即为默认密码（Ab1234567）");
var inputSize = ref(false);
// 新增/编辑
const submitAddEquipForm = async (formEl: FormInstance | undefined) => {
  equipRules.pas = [];

  const {
    eNo,
    eName,
    eEquipName,
    eResponsible,
    eRegion,
    pas,
    role,
    Version,
    ids,
  } = equipForm;
  let roleString;
  if (Array.isArray(role) && role.length === 1 && typeof role[0] === "string") {
    roleString = role[0];
  } else {
    roleString = String(role);
  }
  let pass = ref("");
  if (ishow.value == "1") {
    pass.value = pas ? pas : "A1234567";
  } else if (ishow.value == "2") {
    pass.value = pas;
  }
  const obj = {
    email: eRegion,
    account: eNo,
    name: eName,
    password: pass.value,
    groupId: eEquipName.slice(-1)[0],
    roleId: roseId.value.toString(),
    phone: eResponsible,
    linkGroupParent: JSON.stringify(equipForm.eEquipName),
    objectVersionNumber: Version,
    id: ids,
    linkSystem: "xinfa",
  };

  if (eNo && eEquipName && role) {
    if (ishow.value == 1) {
      let res = await AddProgramUser(obj);
      if (res.data.code == 1) {
        isUploadMaterial.value = false;
        inputSize.value = false;
        ElMessage.success(res.data.msg);
        equipForm.role = "";
        equipFormRef.value.resetFields();
        paging();
        for (let key in equipForm) {
          equipForm[key] = "";
        }
      } else {
        ElMessage.error(res.data.msg);
      }
    } else if (ishow.value == 2) {
      // 修改账户
      let result = await editProgramUser(obj);
      equipForm.role = "";
      paging();

      if (result.data.code == 1) {
        isUploadMaterial.value = false;
        inputSize.value = false;
        ElMessage({
          message: result.data.msg,
          type: "success",
          duration: 1000,
        });
        equipForm.role = "";
        equipFormRef.value.resetFields();

        for (let key in equipForm) {
          equipForm[key] = "";
        }
      } else {
        ElMessage({ message: result.data.msg, type: "error", duration: 1000 });
      }
    }
  }
};
var roseId = ref("");
// 子账户编辑按钮
const editclick = async (val: any) => {
  ishow.value = "2";
  title.value = "编辑账户";
  isUploadMaterial.value = true;
  disableds.value = true;
  placeholders.value = "不填即不修改密码";
  inputSize.value = true;
  let res = await editUser(val.id);
  equipFormRef.value.resetFields();
  equipForm.eNo = res.data.data.account;
  equipForm.eName = res.data.data.name;
  const result = await rolePage();

  treesd.value = convertDatade(result.data.data);
  equipForm.eEquipName = res.data.data.linkGroupParent
    ? JSON.parse(res.data.data.linkGroupParent)
    : "";
  equipForm.role = JSON.stringify(res.data.data.roleId);
  equipForm.eResponsible = res.data.data.phone;
  equipForm.eRegion = res.data.data.email;
  equipForm.Version = res.data.data.objectVersionNumber;
  equipForm.ids = res.data.data.id;
  roseId.value = res.data.data.roleId;
};
//更改分组回调
const isGroupingDialog = shallowRef(false);
const batchGrouping = shallowRef([]);
// 启用
const changeGrouping = async (rows: any) => {
  if (rows) {
    let selectGrouping = unref(multipleTableRef)!.getSelectionRows();
    if (selectGrouping.length > 0) {
      batchGrouping.value = selectGrouping.map((r: any) => r.id);
      let res = await batchPause(batchGrouping.value);
      if ((res.data.code = 1)) {
        paging();
        ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
      } else {
        ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
      }

      isGroupingDialog.value = true;
    } else {
      if (!unref(dropdownGrouping)) return;
      dropdownGrouping.value.handleOpen();
    }
  }
};
// 暂停
const changeGroupings = async (rows: any) => {
  if (rows) {
    let selectGrouping = unref(multipleTableRef)!.getSelectionRows();
    if (selectGrouping.length > 0) {
      batchGrouping.value = selectGrouping.map((r: any) => r.id);
      let res = await batchActivation(batchGrouping.value);
      if ((res.data.code = 1)) {
        paging();
        ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
      } else {
        ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
      }

      isGroupingDialog.value = true;
    } else {
      if (!unref(dropdownGroupings)) return;
      dropdownGroupings.value.handleOpen();
    }
  }
};

// 高级搜索显示隐藏
const AdvancedSearchShow = shallowRef(false);

const texts = ref();
//table复制整条数据弹出按钮
const copyTableObj = async (id: any) => {
  batchGrouping.value = id;
  let res = await batchPause([batchGrouping.value]);
  if ((res.data.code = 1)) {
    paging();
    ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
  } else {
    ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
  }
};
const copyTableObjs = async (id: any) => {
  batchGrouping.value = id;
  let res = await batchActivation([batchGrouping.value]);
  if ((res.data.code = 1)) {
    paging();
    ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
  } else {
    ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
  }
};
//table复制整条数据
const ConfirmCopy = async () => {
  if (form.name) {
    let res = await CopyOpenprogram(texts.value.id, form.name);
    if (res.data.code == 1) {
      ElMessage({ message: "已复制到剪贴板", type: "success", duration: 1000 });
      dialogFormVisible.value = false;
      paging();
    } else {
      ElMessage({ message: "复制失败", type: "error", duration: 1000 });
    }
  }
};
var linkGroupId = ref("");
var pids = ref("");
var objectVersionNumbers = ref("");
const nodeClick = (id: any) => {
  pids.value = id.pid == null ? "0" : id.pid;
  TreeValue.value = id.value; //id
  objectVersionNumbers.value = id.objectVersionNumber; //id
  linkGroupId.value = id.value;
  paging();
};
//请求数据
const getResolution = async () => {
  const { data } = await resolutionList();
  if (data.code !== 1)
    return ElMessage({ message: data.msg, type: "error", duration: 1000 });
  options.value = data.data.map((r: any) => {
    return {
      value: `${r.longResolution}x${r.wideResolution}`,
      label: `${r.longResolution}x${r.wideResolution}`,
    };
  });
};
//分页
const currentPage = ref(1);
const pageSize = ref(10);

var total = ref();

const searchInput = ref("");
const SearchClick = () => {
  paging();
};
const paging = async () => {
  let data = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    keyword: searchInput.value,
    usable: userId.value,
    roleId: equipForm.role,
    groupId: linkGroupId.value,
  };
  let res = await uderPage(data);

  if (res.data.code == 0) {
    ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
    return;
  }
  total = res.data.data.totalElements;
  res.data.data.content.forEach((item: any) => {
    // 将 fileSize 从字节转换为兆字节
    item.fileSize = (item.fileSize / (1024 * 1024)).toFixed(1); // 四舍五入保留两位小数
  });
  // 根据最后一个id 返回所有的lable
  function findParentLabels(data: any, targetValue: any) {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      if (node.value == targetValue) {
        return [node.label]; // 找到目标值，返回当前节点的label
      } else if (node.children && node.children.length > 0) {
        const labels = findParentLabels(node.children, targetValue);

        if (labels.length > 0) {
          return [node.label, ...labels]; // 在子节点中找到目标值，将当前节点的label与子节点的labels一起返回
        }
      }
    }
    return []; // 未找到目标值
  }

  tableData.value = res.data.data.content.map((item: any) => {
    const parentLabels = findParentLabels(trees.value, item.groupId);
    if (parentLabels.length > 1) {
      item.groupId = parentLabels.join("/");
    } else if (parentLabels.length === 1) {
      item.groupId = parentLabels.join("");
    } else if (parentLabels.length < 1) {
      item.groupId = "暂无分组";
    }
    return item;
  });
  // tableData.value = res.data.data.content;
};
//pages
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  paging();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  paging();
};

onMounted(async () => {
  getTreeData();
  getResolution();
  const res = await rolePage();
  treesd.value = convertDatade(res.data.data);

  getTreeData();
  paging();
});
</script>
<style lang="scss" scoped>
.-addEquip_minHead {
  font-weight: 700;
}
::v-deep .wrap_right_list--table-content .el-dropdown-link[data-v-7443f3dc] {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  font-size: 12px;
  margin-left: 12px;
  padding: 7px 11px;
  outline: none;
}
.add {
  width: 3px;
  height: 20px;

  /* 主色 */

  background: #0daeff;
  border-radius: 3px;
  /* Inside auto layout */
  flex: none;
  order: 0;
  flex-grow: 0;
}
::v-deep .el-input input::selection {
  background-color: #79bbff;
}
::v-deep .el-tree-node__content {
  display: flex;
  align-items: center;
  height: 34px;
  cursor: pointer;
}
.program_flex_box {
  width: 100%;
  height: calc(100vh - 100px);
  font-size: 14px;
}
.wrap_left_grouping {
  width: 20%;
  height: 100%;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  color: #303233;
  overflow-y: auto;

  &--head-title {
    height: 56px;
    line-height: 56px;
    border-bottom: 1px solid #f6f7f9;
    white-space: nowrap;
    font-weight: 500;
  }

  &--content-area {
    padding: 20px 5px;

    .edit-child-node {
      width: calc(100% - 10px);
      height: 26px;

      :deep(.el-input__wrapper) {
        background: rgba(255, 255, 255, 0.6);
      }
    }
  }
}
.e-l-dialog_box {
  width: 100%;
  padding: 0 20px;
  overflow: hidden;

  .control_prompt {
    font-weight: 500;
    margin-bottom: 20px;
  }

  .control_content {
    font-weight: 400;
  }

  :deep(.el-menu--horizontal) {
    border-bottom-width: 0;
  }

  .el-menu-demo {
    height: 30px;
  }
}
.wrap_right_list {
  width: 80%;
  height: 100%;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  margin-left: 10px;
  overflow: hidden;
  position: relative;

  &--head-title {
    height: 56px;
    line-height: 56px;
    border-bottom: 1px solid #f6f7f9;
    white-space: nowrap;
    font-weight: 500;
  }

  &--head-operation {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 20px 0;
    overflow: hidden;

    &:hover {
      overflow-x: auto;
    }

    .-row--search {
      display: grid;
      grid-template-areas: "a b c";
    }

    .-dialog-input {
      width: 100%;
      overflow: hidden;

      :deep(.el-form-item__content) {
        max-width: 450px;
      }

      :deep(.el-select) {
        width: 450px;
      }

      .-addDialogFormInput {
        :deep(.el-input) {
          max-width: 190px;
        }
      }
    }
  }

  &--table-content {
    .el-dropdown-link {
      cursor: pointer;
      color: var(--el-color-primary);
      display: flex;
      align-items: center;
      font-size: 12px;
      margin-left: 12px;
      padding: 5 px 11px;
      outline: none;
    }

    .file-child-node {
      width: calc(100% - 40px);
      height: 26px;
    }

    :deep(.el-table__row):hover .--table-column-icon {
      display: inline-block;
    }

    .--table-column-icon {
      display: none;
      margin-left: 10px;
      cursor: pointer;

      &:hover {
        :deep(.el-icon) {
          color: var(--el-color-primary);
        }
      }
    }

    .-pages {
      position: absolute;
      left: 50%;
      bottom: 20px;
      transform: translateX(-50%);
    }

    :deep(.is-background .btn-prev) {
      border: 1px solid var(--el-border-color);
      background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    }

    :deep(.is-background .btn-next) {
      border: 1px solid var(--el-border-color);
      background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    }

    :deep(.el-pager li) {
      border: 1px solid var(--el-border-color);
      background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    }
  }
}
</style>
